<template>
  <view class="space-container">
    <!-- 头部 -->
    <view class="header">
      <text class="title">动态空间</text>
      <view class="header-actions">
        <view class="publish-btn" @click="showPublishModal">
          <text class="publish-icon">✏️</text>
          <text class="publish-text">发布</text>
        </view>
      </view>
    </view>

    <!-- 动态列表 -->
    <scroll-view class="content" scroll-y @scrolltolower="loadMore" refresher-enabled @refresherrefresh="onRefresh">
      <!-- 动态项 -->
      <view class="moment-item" v-for="(moment, index) in momentList" :key="moment.id">
        <!-- 用户信息 -->
         <view class="moment-header">
           <image class="user-avatar" :src="moment.userAvatar" mode="aspectFill" />
           <view class="user-info">
             <text class="user-name">{{ moment.userNickName }}</text>
             <text class="moment-time">{{ formatTime(moment.createdAt) }}</text>
           </view>
           <view class="moment-actions" v-if="moment.userId === currentUserId">
             <view class="action-btn" @click="deleteMoment(index)">
               <text class="action-icon">🗑️</text>
             </view>
           </view>
         </view>

        <!-- 动态内容 -->
        <view class="moment-content">
          <text class="moment-text">{{ moment.content }}</text>
          <!-- 图片 -->
          <view class="moment-images" v-if="moment.images && moment.images.length > 0">
            <image 
              class="moment-image" 
              v-for="(image, imgIndex) in moment.images" 
              :key="imgIndex"
              :src="image" 
              mode="aspectFill"
              @click="previewImage(image, moment.images)"
            />
          </view>
        </view>

        <!-- 互动区域 -->
        <view class="moment-interactions">
          <view class="interaction-item" @click="toggleLike(index)">
            <text class="interaction-icon" :class="{ 'liked': moment.isLiked }">❤️</text>
            <text class="interaction-text">{{ moment.likeCount || 0 }}</text>
          </view>
          <view class="interaction-item" @click="showCommentInput(index)">
            <text class="interaction-icon">💬</text>
            <text class="interaction-text">{{ moment.commentCount || 0 }}</text>
          </view>
        </view>

        <!-- 评论列表 -->
        <view class="comment-list" v-if="moment.comments && moment.comments.length > 0">
          <view class="comment-item" v-for="(comment, commentIndex) in moment.comments" :key="comment.id">
            <image class="comment-avatar" :src="comment.userAvatar" mode="aspectFill" />
            <view class="comment-content">
              <view class="comment-header">
                <text class="comment-user">{{ comment.userNickName }}</text>
                <text class="comment-time">{{ formatTime(comment.createdAt) }}</text>
              </view>
              <text class="comment-text">{{ comment.content }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view class="load-more" v-if="momentList.length > 0">
        <view class="load-more-content" v-if="loading">
          <text class="loading-text">加载中...</text>
        </view>
        <view class="load-more-content" v-else-if="!hasMore">
          <text class="no-more-text">没有更多了</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="momentList.length === 0 && !loading">
        <text class="empty-icon">📝</text>
        <text class="empty-text">还没有动态</text>
        <text class="empty-hint">发布第一条动态分享生活吧！</text>
      </view>
    </scroll-view>

    <!-- 发布动态弹窗 -->
    <view class="publish-modal" v-if="showPublish" @click="hidePublishModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">发布动态</text>
          <view class="modal-close" @click="hidePublishModal">
            <text class="close-icon">✕</text>
          </view>
        </view>
        <view class="modal-body">
          <textarea 
            class="publish-input" 
            v-model="publishContent" 
            placeholder="分享你的生活..." 
            :maxlength="500"
            auto-height
          />
          <view class="publish-tools">
            <view class="tool-item" @click="selectImages">
              <text class="tool-icon">📷</text>
              <text class="tool-text">图片</text>
            </view>
          </view>
          <view class="char-count">
            <text class="count-text" :class="{ 'warning': publishContent.length > 450 }">
              {{ publishContent.length }}/500
            </text>
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="hidePublishModal">
            <text class="btn-text">取消</text>
          </view>
          <view class="confirm-btn" :class="{ 'disabled': !canPublish }" @click="publishMoment">
            <text class="btn-text">发布</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 评论输入弹窗 -->
    <view class="comment-modal" v-if="showComment" @click="hideCommentModal">
      <view class="comment-input-container" @click.stop>
        <textarea 
          class="comment-input" 
          v-model="commentContent" 
          placeholder="写下你的评论..." 
          :maxlength="200"
          auto-focus
        />
        <view class="comment-actions">
          <view class="comment-cancel" @click="hideCommentModal">
            <text class="action-text">取消</text>
          </view>
          <view class="comment-send" :class="{ 'disabled': !canComment }" @click="sendComment">
            <text class="action-text">发送</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { AuthUtils } from '@/utils/auth'
import { PostAPI } from '@/utils/api'

// 用户信息
const userInfo = computed(() => AuthUtils.getUserInfo())
const currentUserId = computed(() => userInfo.value?.userId || '')

// 动态数据接口
interface User {
  id: string
  name: string
  avatar: string
}

interface Comment {
  id: string | number
  postId: string | number
  userId: string
  userNickName: string
  userAvatar: string
  content: string
  parentId?: string | number
  parentComment?: Comment | null
  createdAt: string
  replyCount?: number
  replies?: Comment[]
}

interface Moment {
  id: string | number
  userId: string
  userNickName: string
  userAvatar: string
  content: string
  images?: string[]
  likeCount: number
  commentCount: number
  isLiked: boolean
  createdAt: string
  comments?: Comment[]
}

// 响应式数据
const momentList = ref<Moment[]>([])
const showPublish = ref(false)
const showComment = ref(false)
const publishContent = ref('')
const commentContent = ref('')
const currentMomentIndex = ref(-1)

// 分页相关
const page = ref(1)
const hasMore = ref(true)
const loading = ref(false)

// 计算属性
const canPublish = computed(() => {
  return publishContent.value.trim().length > 0
})

const canComment = computed(() => {
  return commentContent.value.trim().length > 0
})

// 格式化时间
const formatTime = (timestamp: string): string => {
  const time = new Date(timestamp)
  const now = new Date()
  const diffMs = now.getTime() - time.getTime()
  const diffMinutes = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffMinutes < 1) {
    return '刚刚'
  } else if (diffMinutes < 60) {
    return `${diffMinutes}分钟前`
  } else if (diffHours < 24) {
    return `${diffHours}小时前`
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return time.toLocaleDateString('zh-CN')
  }
}

// 显示发布弹窗
const showPublishModal = () => {
  showPublish.value = true
}

// 隐藏发布弹窗
const hidePublishModal = () => {
  showPublish.value = false
  publishContent.value = ''
}

// 发布动态
const publishMoment = async () => {
  if (!canPublish.value) return
  
  if (publishContent.value.length > 1000) {
    uni.showToast({
      title: '内容长度不能超过1000个字符',
      icon: 'none'
    })
    return
  }
  
  try {
    const response = await PostAPI.createPost(publishContent.value.trim())
  
    if (response.code === 200) {
      hidePublishModal()
      
      // 重新获取动态列表以确保数据同步
      await loadMoments(true)
      
      uni.showToast({
        title: '发布成功',
        icon: 'success'
      })
    } else {
      throw new Error(response.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    
    uni.showToast({
      title: error.message || '发布失败',
      icon: 'error'
    })
  }
}

// 删除动态
const deleteMoment = (index: number) => {
  const moment = momentList.value[index]
  
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条动态吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await PostAPI.deletePost(moment.id)
          
          if (response.code === 200) {
            // 重新获取动态列表以确保数据同步
            await loadMoments(true)
            
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
          } else {
            throw new Error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除动态失败:', error)
          
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

// 切换点赞状态
const toggleLike = async (index: number) => {
  const moment = momentList.value[index]
  const originalLiked = moment.isLiked
  const originalCount = moment.likeCount
  
  // 乐观更新UI
  moment.isLiked = !moment.isLiked
  moment.likeCount += moment.isLiked ? 1 : -1
  
  try {
    const response = await PostAPI.toggleLike(moment.id)
    
    if (response.code===200) {
      // 使用服务器返回的准确数据
      moment.isLiked = response.data.isLiked
      moment.likeCount = response.data.likeCount
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    
    // 回滚UI状态
    moment.isLiked = originalLiked
    moment.likeCount = originalCount
    
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'error'
    })
  }
}

// 显示评论输入
const showCommentInput = (index: number) => {
  currentMomentIndex.value = index
  showComment.value = true
}

// 隐藏评论输入
const hideCommentModal = () => {
  showComment.value = false
  commentContent.value = ''
  currentMomentIndex.value = -1
}

// 发送评论
const sendComment = async () => {
  if (!canComment.value || currentMomentIndex.value === -1) return
  
  if (commentContent.value.trim().length > 500) {
    uni.showToast({
      title: '评论内容不能超过500个字符',
      icon: 'none'
    })
    return
  }
  
  const moment = momentList.value[currentMomentIndex.value]
  
  try {
    const response = await PostAPI.createComment(moment.id, commentContent.value.trim())
    
    if (response.code === 200) {
      hideCommentModal()
      
      // 重新获取动态列表以确保数据同步
      await loadMoments(true)
      
      uni.showToast({
        title: '评论成功',
        icon: 'success'
      })
    } else {
      throw new Error(response.message || '评论失败')
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    
    uni.showToast({
      title: error.message || '评论失败',
      icon: 'error'
    })
  }
}

// 选择图片
const selectImages = () => {
  uni.chooseImage({
    count: 9,
    success: (res) => {
      console.log('选择图片:', res.tempFilePaths)
      uni.showToast({
        title: '图片功能开发中',
        icon: 'none'
      })
    }
  })
}

// 预览图片
const previewImage = (current: string, urls: string[]) => {
  uni.previewImage({
    current,
    urls
  })
}

// 加载动态列表
const loadMoments = async (refresh = false) => {
  if (loading.value) return
  
  if (refresh) {
    page.value = 1
    hasMore.value = true
  }
  
  loading.value = true
  try {
    console.log('开始获取')
    const response = await PostAPI.getFriendsPosts({
      page: page.value,
      limit: 10
    })
    console.log(response,'res')
    if (response.code===200) {
      const { posts, pagination } = response.data
      
      if (refresh || page.value === 1) {
        momentList.value = posts
      } else {
        momentList.value.push(...posts)
      }
      
      hasMore.value = pagination.page < pagination.totalPages
      page.value = pagination.page + 1
    } else {
      throw new Error(response.message || '获取动态失败')
    }
  } catch (error) {
    console.error('加载动态失败:', error)
    
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadMoments()
  }
}

// 下拉刷新
const onRefresh = () => {
  loadMoments(true)
}

// 页面加载
onMounted(() => {
  // 检查登录状态
  if (!AuthUtils.isLoggedIn()) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    uni.reLaunch({
      url: '/pages/login'
    })
    return
  }
  
  // 加载动态数据
  loadMoments()
})
</script>

<style scoped>
.space-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: calc(120rpx + env(safe-area-inset-top));
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: env(safe-area-inset-top) 30rpx 0;
  border-bottom: 1rpx solid #e5e5e5;
  z-index: 100;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
}

.header-actions {
  display: flex;
  align-items: center;
}

.publish-btn {
  display: flex;
  align-items: center;
  background-color: #007AFF;
  padding: 12rpx 24rpx;
  border-radius: 40rpx;
}

.publish-icon {
  font-size: 24rpx;
  margin-right: 8rpx;
}

.publish-text {
  font-size: 28rpx;
  color: #ffffff;
  font-weight: 500;
}

/* 内容区域 */
.content {
  flex: 1;
  padding: calc(140rpx + env(safe-area-inset-top)) 0 calc(env(safe-area-inset-bottom));
}

/* 动态项样式 */
.moment-item {
  background-color: #ffffff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.moment-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  margin-right: 20rpx;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  display: block;
  margin-bottom: 8rpx;
}

.moment-time {
  font-size: 24rpx;
  color: #999999;
}

.moment-actions {
  display: flex;
  align-items: center;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
  background-color: #f5f5f5;
}

.action-icon {
  font-size: 24rpx;
}

/* 动态内容 */
.moment-content {
  margin-bottom: 20rpx;
}

.moment-text {
  font-size: 30rpx;
  color: #333333;
  line-height: 1.6;
  display: block;
  margin-bottom: 20rpx;
}

.moment-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.moment-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
}

/* 互动区域 */
.moment-interactions {
  display: flex;
  align-items: center;
  gap: 40rpx;
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
}

.interaction-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.interaction-icon {
  font-size: 32rpx;
  transition: transform 0.2s;
}

.interaction-icon.liked {
  color: #ff4757;
  transform: scale(1.1);
}

.interaction-text {
  font-size: 28rpx;
  color: #666666;
}

/* 评论列表 */
.comment-list {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.comment-item {
  display: flex;
  margin-bottom: 20rpx;
}

.comment-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-right: 15rpx;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 15rpx;
  margin-bottom: 8rpx;
}

.comment-user {
  font-size: 26rpx;
  font-weight: 500;
  color: #333333;
}

.comment-time {
  font-size: 22rpx;
  color: #999999;
}

.comment-text {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.5;
}

/* 加载更多 */
.load-more {
  padding: 30rpx;
  text-align: center;
}

.load-more-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
}

.no-more-text {
  font-size: 28rpx;
  color: #cccccc;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 30rpx;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #666666;
  margin-bottom: 15rpx;
}

.empty-hint {
  font-size: 26rpx;
  color: #999999;
}

/* 发布弹窗 */
.publish-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.modal-close {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
  background-color: #f5f5f5;
}

.close-icon {
  font-size: 24rpx;
  color: #666666;
}

.modal-body {
  padding: 30rpx;
}

.publish-input {
  width: 100%;
  min-height: 200rpx;
  font-size: 30rpx;
  color: #333333;
  line-height: 1.6;
  border: none;
  outline: none;
  resize: none;
  background-color: transparent;
}

.publish-tools {
  display: flex;
  align-items: center;
  gap: 30rpx;
  margin: 30rpx 0;
}

.tool-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 15rpx 20rpx;
  border-radius: 40rpx;
  background-color: #f5f5f5;
}

.tool-icon {
  font-size: 24rpx;
}

.tool-text {
  font-size: 26rpx;
  color: #666666;
}

.char-count {
  text-align: right;
}

.count-text {
  font-size: 24rpx;
  color: #999999;
}

.count-text.warning {
  color: #ff4757;
}

.modal-footer {
  display: flex;
  border-top: 1rpx solid #e5e5e5;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  border-right: 1rpx solid #e5e5e5;
}

.confirm-btn {
  background-color: #007AFF;
}

.confirm-btn.disabled {
  background-color: #cccccc;
}

.btn-text {
  font-size: 30rpx;
  color: #666666;
}

.confirm-btn .btn-text {
  color: #ffffff;
}

/* 评论弹窗 */
.comment-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.comment-input-container {
  width: 100%;
  background-color: #ffffff;
  padding: 30rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  border-radius: 20rpx 20rpx 0 0;
}

.comment-input {
  width: 100%;
  min-height: 120rpx;
  font-size: 30rpx;
  color: #333333;
  line-height: 1.6;
  border: 1rpx solid #e5e5e5;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.comment-cancel,
.comment-send {
  padding: 15rpx 30rpx;
  border-radius: 40rpx;
  border: 1rpx solid #e5e5e5;
}

.comment-send {
  background-color: #007AFF;
  border-color: #007AFF;
}

.comment-send.disabled {
  background-color: #cccccc;
  border-color: #cccccc;
}

.action-text {
  font-size: 28rpx;
  color: #666666;
}

.comment-send .action-text {
   color: #ffffff;
 }
</style>